package cqie.cn.frame.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cqie.cn.frame.utils.RetJson;
import cqie.cn.frame.utils.RetJsonUtils;
import cqie.cn.frame.entity.*;
import cqie.cn.frame.entity.po.SysRolePo;
import cqie.cn.frame.service.IRoleMenuService;
import cqie.cn.frame.service.ISysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 王林
 * @since 2021-09-03
 */
@Api(tags = "01系统管理--03系统角色")
@RestController
@RequestMapping("/api/frame/sysRole")
public class SysRoleController {

    @Resource
    private ISysRoleService roleService;

    @Resource
    private IRoleMenuService roleMenuService;

    //新增角色
    @ApiOperation(value = "新增角色", notes = "", response = SysRolePo.class)
    @GetMapping("/add")
    public RetJson add(SysRolePo po) {
        try {
            SysRole mo = new SysRole();
            BeanUtils.copyProperties(mo, po);
            roleService.save(mo);
            //2-构造返回值
            po.setId(mo.getId());
            if (po.getMenuIdList() != null) {
                ArrayList<RoleMenu> roleMenuList = new ArrayList<>();
                po.getMenuIdList().forEach(x -> {
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setMenuId(x);
                    roleMenu.setRoleId(mo.getId());//mybatis 新增后 会回写id
                    roleMenuList.add(roleMenu);
                });
                roleMenuService.saveBatch(roleMenuList);
            }
            return RetJsonUtils.success("添加成功", mo);
        } catch (Exception e) {
            return RetJsonUtils.error(e.getMessage());
        }
    }

    //删除角色
    @ApiOperation(value = "删除角色", notes = "")
    @DeleteMapping("/remove")
    public RetJson remove(Integer roleId) {

        try {
            QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
            wrapper.eq("roleId", roleId);
            roleService.remove(wrapper);
            return RetJsonUtils.success("删除成功");
        } catch (Exception e) {
            return RetJsonUtils.error(e.getMessage());
        }
    }

    //修改角色
    @ApiOperation(value = "修改角色", notes = "")
    @PutMapping("/edit")
    public RetJson edit(SysRole role) {
        try {
            roleService.updateById(role);
            return RetJsonUtils.success("修改成功");
        } catch (Exception e) {
            return RetJsonUtils.error(e.getMessage());
        }
    }

}

